# -*- coding: utf-8 -*-
class FeeController < ApplicationController
  before_filter :user_authorize,:except =>[:login,:validate_user]
  before_filter :sys_before_log

  def validate_user
    userName = params[:name]
    password = params[:password]
    user = User.find(:first,:conditions => ["name = ? AND password = ? AND is_locked <> 1",userName,password])
    if user == nil
      info="登录失败!"
    else
      session[:user_id] = user.id
      session[:user_name] = user.name
      session[:user_type] = user.sub_type
      prices = Price.all
      prices.each do |price|
        if price.sub_type =="多层物业费"
          session[:multi_property_unit_price] = price.price
        elsif price.sub_type =="高层物业费"
          session[:high_property_unit_price] = price.price
        elsif price.sub_type =="电梯费"
          session[:lift_unit_price] = price.price
        elsif price.sub_type =="水费"
          session[:water_unit_price] = price.price
        end
      end
      
      info="登录成功"
    end
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  def logout
    reset_session
    info="退出成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end
  
  #所有的费用的操作，不再单独设立controller了，只用这一个统一管理即可。
  #  new：下发一个空页面，以准备添加新记录
  #  create：增加
  #  edit：编辑前的数据查询准备
  #  update：编辑后更新数据到数据库
  #  destroy：删除
  #  index：某controller下，用于显示所有记录信息。
  #  show：仅仅显示某个单独的项
  def newWaterFeeRecord
    houseId = params[:house_id]
    @house = House.find(houseId)
    puts @house.id
    puts @house.water_pay_year
    @waterMeter = WaterMeter.find(:first,:conditions=>["house_id = ? AND is_paid = 0",houseId],:order=>"id desc")
    puts @waterMeter
  end

  def editWaterFeeRecord
    
    houseId = params[:house_id]
    @house = House.find(houseId)
    @waterId = params[:water_id]
  end
  
  #追加一条新的水费交款记录
  def createWaterFeeRecord
    
    houseId = params[:house_id].to_i
    waterFeeRecord = Water.new
    house = House.find(houseId)    
    
    waterFeeRecord.last_year = house.water_pay_year
    waterFeeRecord.last_month = house.water_pay_month
    waterFeeRecord.current_year = params[:current_year]
    waterFeeRecord.current_month = params[:current_month]
    
    waterFeeRecord.unit_price = params[:unit_price]
    waterFeeRecord.last_meter = house.water_last_meter
    waterFeeRecord.current_meter = params[:current_meter]
    waterFeeRecord.quantity = params[:current_meter].to_f - house.water_last_meter
    #本次抄表日期
    waterFeeRecord.meter_recording_date = params[:meter_recording_date]
    waterFeeRecord.action_date = Time.new.strftime("%Y-%m-%d %H:%M:%S")
    waterFeeRecord.amount = params[:amount]
    #得到付款方式0余额，1现金，2混合，即还有余额但不够，从现金中补。
    paymentMethod = params[:payment_method]

    #记录最后一次的Balance
    waterFeeRecord.last_balance =  house.balance
    if paymentMethod == "余额"
      house.balance = house.balance - params[:amount].to_f
      waterFeeRecord.use_balance =  params[:amount].to_f
      waterFeeRecord.payment_method = "余额"
    elsif paymentMethod =="现金" #现金支付
      waterFeeRecord.use_cash = params[:amount].to_f
      waterFeeRecord.payment_method = "现金"
    elsif paymentMethod =="混合"
      waterFeeRecord.use_balance =  house.balance
      waterFeeRecord.use_cash =  params[:amount].to_f - house.balance
      house.balance = 0
      waterFeeRecord.payment_method = "混合"
    end

    waterFeeRecord.balance = house.balance
    #追加编辑人员信息
    waterFeeRecord.user_id = session[:user_id]
    house.water_pay_year = params[:current_year]
    house.water_pay_month = params[:current_month]
    house.water_last_meter = params[:current_meter]
    #保存相关记录
    house.waters << waterFeeRecord
    #把用户已经交费的记录，更新到抄表表中。
    #上次交费日期
    waterRecordLastDate =  waterFeeRecord.last_year*100 + waterFeeRecord.last_month
    #本次交费日期
    WaterMeter.update_all("is_paid = 1",["house_id = ? AND ((current_year*100+current_month) >= ?)",houseId, waterRecordLastDate])
    house.save
    
    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  def updateWaterFeeRecord
    
    houseId = params[:house_id]
    waterFeeRecord = Water.find(params[:id])
    house = House.find(houseId)

    #waterFeeRecord.last_year = house.water_pay_year
    #waterFeeRecord.last_month = house.water_pay_month
    waterFeeRecord.current_year = params[:current_year]
    waterFeeRecord.current_month = params[:current_month]

    waterFeeRecord.unit_price = params[:unit_price]
    #waterFeeRecord.last_meter = house.water_last_meter
    waterFeeRecord.current_meter = params[:current_meter]
    waterFeeRecord.quantity = params[:current_meter].to_f - waterFeeRecord.last_meter
    #本次抄表日期
    waterFeeRecord.meter_recording_date = params[:meter_recording_date]
    waterFeeRecord.action_date = Time.new.strftime("%Y-%m-%d %H:%M:%S")
    waterFeeRecord.amount = params[:amount]
    #得到付款方式0余额，1现金，2混合，即还有余额但不够，从现金中补。
    paymentMethod = params[:payment_method]
    #在处理余额时要注意一项，即在收费和编辑状态之间，用户有可能对余额进行充值。
    #这时在编辑时要对此作特殊处理，比如要比较当前的余额和house表中的余额是否相等
    #如果不相等说明有余额充入。
    #其实这里面要作很多判断，一是当前用户改成什么支付方式了，二是他上一次用的什么支持方式
    #如果简介起见的话，可以设定用户在修改时，不得修改支持方式。
    if paymentMethod == "余额"
      if house.balance == waterFeeRecord.balance
        house.balance = waterFeeRecord.last_balance - params[:amount].to_f
      else
        house.balance = house.balance - waterFeeRecord.balance + waterFeeRecord.last_balance - params[:amount].to_f
      end
      waterFeeRecord.use_balance =  params[:amount].to_f
      waterFeeRecord.payment_method = "余额"
    elsif paymentMethod =="现金" #现金支付
      #用现金时，不用操作余额
      waterFeeRecord.last_balance = house.balance
      waterFeeRecord.balance = house.balance
      waterFeeRecord.use_cash = params[:amount].to_f
      waterFeeRecord.payment_method = "现金"
    elsif paymentMethod =="混合"
      lastAmount = waterFeeRecord.amount
      currentAmount = params[:amount].to_f
      #用混合时，还原上次的可能的余额。
      #如果在编辑时用户退过款，从前台的控制来讲，只能改动现金，不可再改动余额
      #如果余额被充值过，刚先求出到底充了多少余额。house.balance - waterFeeRecord.balance
      #所以这一次余额是不能动的，只能退或补现金
      #为负数，就是要退别人的现金。为正数不一定，为正数就是手工让收费员自己看看如何把钱找出差来。
      waterFeeRecord.use_cash =  params[:amount].to_f - waterFeeRecord.use_balance
      waterFeeRecord.payment_method = "混合"
    end

    waterFeeRecord.balance = house.balance
    #追加编辑人员信息
    waterFeeRecord.user_id = session[:user_id]
    house.water_pay_year = params[:current_year]
    house.water_pay_month = params[:current_month]
    house.water_last_meter = params[:current_meter]
    #保存相关记录
    house.waters << waterFeeRecord
    house.save

    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end
  
  def getWaterById
    
    water = Water.find(params[:water_id])
    jsonStr = "{root:["+water.to_json(:include=>[:house])+"]}"
    puts jsonStr
    render :text=>jsonStr, :layout=>false
  end
  
  #=============================================================================
  #新物业费交费准备
  def newPropertyRecord
    
    houseId = params[:house_id]
    @house = House.find(houseId)
  end

  #追加一条新的水费交款记录
  def createPropertyRecord
    
    houseId = params[:house_id]
    propertyRecord = Property.new
    house = House.find(houseId)

    propertyRecord.last_year = house.property_pay_year
    propertyRecord.last_month = house.property_pay_month
    propertyRecord.current_year = params[:current_year]
    propertyRecord.current_month = params[:current_month]

    propertyRecord.area = params[:area]
    propertyRecord.unit_price = params[:unit_price]
    propertyRecord.amount = params[:amount]
    propertyRecord.user_id = session[:user_id]
    propertyRecord.action_date = Time.new.strftime("%Y-%m-%d %H:%M:%S")
    house.property_pay_year = params[:current_year]
    house.property_pay_month = params[:current_month]
    
    #保存相关记录
    house.properties << propertyRecord
    house.save

    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  def editPropertyRecord
    
    @house = House.find(params[:house_id])
    @propertyId = params[:property_id]
  end

  def updatePropertyRecord
    
    houseId = params[:house_id]
    propertyRecord = Property.find(params[:id])
    house = House.find(houseId)

    #propertyRecord.last_year = house.property_pay_year
    #propertyRecord.last_month = house.property_pay_month
    propertyRecord.current_year = params[:current_year]
    propertyRecord.current_month = params[:current_month]

    propertyRecord.unit_price = params[:unit_price]
    propertyRecord.amount = params[:amount]
    propertyRecord.user_id = session[:user_id]
    propertyRecord.action_date = Time.new.strftime("%Y-%m-%d %H:%M:%S")
    
    house.property_pay_year = params[:current_year]
    house.property_pay_month = params[:current_month]

    #保存相关记录
    house.properties << propertyRecord
    house.save

    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  def getPropertyById
    
    property = Property.find(params[:property_id])
    jsonStr = "{root:["+property.to_json(:include=>[:house])+"]}"
    puts jsonStr
    render :text=>jsonStr, :layout=>false
  end
  
  #新电梯费交费准备
  def newLiftRecord
    
    houseId = params[:house_id]
    @house = House.find(houseId)
  end

  def editLiftRecord
    
    @house = House.find(params[:house_id])
    @liftId = params[:lift_id]
  end
  
  #追加一条新的电梯费交款记录
  def createLiftRecord
    
    houseId = params[:house_id]
    liftRecord = Lift.new
    house = House.find(houseId)


    liftRecord.last_year = house.lift_pay_year
    liftRecord.last_month = house.lift_pay_month
    liftRecord.current_year = params[:current_year]
    liftRecord.current_month = params[:current_month]

    liftRecord.area = params[:area]
    liftRecord.unit_price = params[:unit_price]
    liftRecord.amount = params[:amount]
    liftRecord.user_id = session[:user_id]
    liftRecord.action_date = Time.new.strftime("%Y-%m-%d %H:%M:%S")
    
    house.lift_pay_year = params[:current_year]
    house.lift_pay_month = params[:current_month]

    #保存相关记录
    house.lifts << liftRecord
    house.save

    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end
  
  def updateLiftRecord
    
    houseId = params[:house_id]
    liftRecord = Lift.find(params[:id])
    house = House.find(houseId)

    #liftRecord.last_year = house.lift_pay_year
    #liftRecord.last_month = house.lift_pay_month
    liftRecord.current_year = params[:current_year]
    liftRecord.current_month = params[:current_month]

    liftRecord.unit_price = params[:unit_price]
    liftRecord.amount = params[:amount]
    liftRecord.user_id = session[:user_id]
    liftRecord.action_date = Time.new.strftime("%Y-%m-%d %H:%M:%S")

    house.lift_pay_year = params[:current_year]
    house.lift_pay_month = params[:current_month]

    #保存相关记录
    house.lifts << liftRecord
    house.save

    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  def getLiftById
    
    lift = Lift.find(params[:lift_id])
    jsonStr = "{root:["+lift.to_json(:include=>[:house])+"]}"
    render :text=>jsonStr, :layout=>false
  end
  
  def getAllProperties
    
    houseId = params[:house_id]
    puts houseId
    properties = Property.where("house_id = ?",houseId)
    jsonStr="{totalProperty:"+properties.length.to_s+",root:"+properties.to_json(:include=>[:user])+"}"
    puts jsonStr
    render :text=>jsonStr, :layout=>false
  end

  def getAllLifts
    
    houseId = params[:house_id]
    lifts = Lift.where("house_id = ?",houseId)
    jsonStr="{totalProperty:"+lifts.length.to_s+",root:"+lifts.to_json(:include=>[:user])+"}"
    puts jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #得到某业主的所有交费记录
  def getAllWaters
    
    houseId = params[:house_id]
    waters = Water.where("house_id = ?",houseId)
    jsonStr="{totalProperty:"+waters.length.to_s+",root:"+waters.to_json(:include=>[:user])+"}"
    puts jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #得到某业主的所有水费充值记录
  def getAllWaterRecharges
    
    houseId = params[:house_id]
    puts houseId
    waterRecharges = WaterRecharge.where("house_id = ?",houseId)
    puts waterRecharges.length
    jsonStr="{totalProperty:"+waterRecharges.length.to_s+",root:"+waterRecharges.to_json(:include=>[:user])+"}"
    puts jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #新物业费交费准备
  def newWaterRechargeRecord
    
    @houseId = params[:house_id]
  end

  def createWaterRechargeRecord
    
    houseId = params[:house_id]
    house = House.find(houseId)
    waterRecharge = WaterRecharge.new
    waterRecharge.amount = params[:amount]
    waterRecharge.balance = house.balance + params[:amount].to_f
    waterRecharge.user_id = session[:user_id]
    house.water_recharges << waterRecharge
    house.balance = house.balance + params[:amount].to_f
    house.save
    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end
end
